package com.ruoyi.web.controller.fund;

import com.ruoyi.account.domain.HouseAccountT;
import com.ruoyi.account.service.IHouseAccountTService;
import com.ruoyi.common.annotation.Log;
import com.ruoyi.common.config.RuoYiConfig;
import com.ruoyi.common.core.controller.BaseController;
import com.ruoyi.common.core.domain.AjaxResult;
import com.ruoyi.common.core.page.TableDataInfo;
import com.ruoyi.common.enums.BusinessType;
import com.ruoyi.common.utils.poi.ExcelUtil;
import com.ruoyi.data.DataUtils;
import com.ruoyi.http.service.IWeChatTService;
import com.ruoyi.project.domain.ParameterSingleVO;
import com.ruoyi.project.service.IHouseProjectTService;
import com.ruoyi.util.FileUtil;
import com.ruoyi.util.SysParamKey;
import org.apache.commons.lang3.time.DateFormatUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpServletResponse;
import java.io.*;
import java.net.URL;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;

/**
 * 对账Controller
 * 
 * @author ruoyi
 * @date 2023-09-07
 */
@RestController
@RequestMapping("/cost/account")
public class HouseAccountTController extends BaseController
{
    @Autowired
    private IHouseAccountTService houseAccountTService;
    @Autowired
    private IHouseProjectTService houseProjectTService;
    @Autowired
    private IWeChatTService weChatTService;

    private ParameterSingleVO parameterSingleVO = new ParameterSingleVO();
    private ParameterSingleVO parameterSingleVO1 = new ParameterSingleVO();
    private String urlFile = "111.26.101.245:12348/";
    private String generateFileName;
    private HttpServletResponse response;

    //请求文件
    @GetMapping("/requestFile/{datetime}")
    public AjaxResult requestFile(@PathVariable("datetime") Date datetime) throws IOException {
        String datetime2= DateFormatUtils.format(datetime, "yyyyMMdd");
        String path = RuoYiConfig.getDateAccount();
        String path1 = RuoYiConfig.getGetAccount();
        String filePath = path1 + "house" + datetime2 + "weixin.txt";
        File checkFile = new File("");
        checkFile = new File(path + "house" + datetime2 + "weixin.txt");
        StringBuffer stringBuffer = new StringBuffer();
        if (!checkFile.exists()) {
            System.out.println(filePath);
            URL url = new URL(filePath);
            BufferedReader reader = new BufferedReader(new InputStreamReader(url.openStream()));
            Integer dataInt = 0;
            String buffer = "";
            buffer = reader.readLine();
            while (buffer != null) { //行数不为空
                String[] bufferStr = buffer.split("\\|");
                if (bufferStr[0].isEmpty() || bufferStr[1].isEmpty() || bufferStr[2].isEmpty() || bufferStr[3].isEmpty()|| bufferStr[4].isEmpty()) {
                    String returnMsg = "第" + dataInt + "条数据错误！";
                    logger.info(returnMsg);
                    return AjaxResult.error(returnMsg);
                }
                String rcvAmt = String.valueOf(DataUtils.divideMoney(Double.valueOf(bufferStr[1].trim()), 100d)); //缴费金额
                stringBuffer.append(bufferStr[0].trim() + "|" + bufferStr[1].trim()
                        + "|" + bufferStr[2].trim() + "|" + bufferStr[3].trim()+ "|" + bufferStr[4].trim());
                stringBuffer.append("\r\n");
                dataInt++;
                buffer = reader.readLine();
            }
            FileUtil.stringToTxt(stringBuffer.toString(), path + "house" + datetime2 + "weixin.txt");
/*            Map<String, String> map1 = new HashMap<String, String>();
            map1.put("addr", urlFile + generateFileName);
            return AjaxResult.success(map1);*/
            return AjaxResult.success("{success:true}", response);
        } else {
            return AjaxResult.error("请确认对账文件！");
        }
    }
    //重新对账
    @GetMapping("/checkAccount/{datetime}")
    public AjaxResult checkAccount(@PathVariable("datetime")  Date datetime) throws IOException {
        String datetime1=DateFormatUtils.format(datetime, "yyyyMMdd");
        String  costWay="3";
        List<HouseAccountT> costList = new ArrayList<HouseAccountT>();
        String path = RuoYiConfig.getDateAccount();
        File checkFile = new File("");
        checkFile = new File(path + "house" + datetime1 + "weixin.txt");
        if (checkFile.exists()) {
            try {
                BufferedReader input = new BufferedReader(new FileReader(checkFile));
                String buffer = input.readLine();
                int dataInt = 1;
                while (buffer != null) {
                    HouseAccountT accountCheckVO = new HouseAccountT();
                    String[] bufferStr = buffer.split("\\|");
                    if (bufferStr[0].isEmpty() || bufferStr[1].isEmpty() || bufferStr[2].isEmpty()
                            || bufferStr[3].isEmpty()|| bufferStr[4].isEmpty()) {
                        String returnMsg = "第" + dataInt + "条数据错误！";
                        logger.info(returnMsg);
                        return AjaxResult.error(returnMsg + "对账失败");
                    }
                    dataInt++;
                    accountCheckVO.setHouseid(bufferStr[0]);
                    accountCheckVO.setCostMoney(Double.valueOf(bufferStr[1]));
                    accountCheckVO.setOrderid(bufferStr[2]);
                    accountCheckVO.setCostdate(bufferStr[3]);
                    accountCheckVO.setSerial(bufferStr[4]);
                    if (!bufferStr[3].equals(datetime1)) {
                        String returnMsg = "第" + dataInt + "条数据错误,非本日数据！";
                        logger.info(returnMsg);
                        return AjaxResult.error(returnMsg+"请确认对账文件！");
                    } else {
                        costList.add(accountCheckVO);
                    }
                    buffer = input.readLine();
                }
                houseAccountTService.checkAccount(costList,datetime1,costWay);
            }catch (Exception e) {
                return AjaxResult.error("批量格式错误，请确认！");
            }
            return AjaxResult.success("{success:true}", response);
        }else{
            return AjaxResult.error("请确认对账文件！");
        }
    }

    /**
     * 查询对账列表
     */
    @GetMapping("/list")
    public TableDataInfo list(HouseAccountT houseAccountT)
    {
        startPage();
        List<HouseAccountT> list = houseAccountTService.selectHouseAccountTList(houseAccountT);
        return getDataTable(list);
    }

    /**
     * 导出对账列表
     */
    @Log(title = "对账", businessType = BusinessType.EXPORT)
    @PostMapping("/export")
    public void export(HttpServletResponse response, HouseAccountT houseAccountT)
    {
        List<HouseAccountT> list = houseAccountTService.selectHouseAccountTList(houseAccountT);
        ExcelUtil<HouseAccountT> util = new ExcelUtil<HouseAccountT>(HouseAccountT.class);
        util.exportExcel(response, list, "对账数据");
    }

    /**
     * 获取对账详细信息
     */
    @GetMapping(value = "/{id}")
    public AjaxResult getInfo(@PathVariable("id") Long id)
    {
        return AjaxResult.success(houseAccountTService.selectHouseAccountTById(id));
    }
    /**
     * 修改对账
     */
    @Log(title = "对账", businessType = BusinessType.UPDATE)
    @PutMapping
    public AjaxResult edit(@RequestBody HouseAccountT houseAccountT)
    {
        return toAjax(houseAccountTService.updateHouseAccountT(houseAccountT));
    }

    /**
     * 删除对账
     */
    @Log(title = "对账", businessType = BusinessType.DELETE)
	@DeleteMapping("/{ids}")
    public AjaxResult remove(@PathVariable Long[] ids)
    {
        return toAjax(houseAccountTService.deleteHouseAccountTByIds(ids));
    }

}
